const UserService = require("../service/UserServer");
const GameService = require("../service/GameServer");
const JWT = require("../util/JWT")
const fs = require('fs');

const UserContoller = {
    userInf: async (req, res) => {
        //解析token 获取id
        let payload = JWT.verify(req.headers["authorization"].split(" ")[1])
        const result = await UserService.userInf(payload._id);
        const result2 = await GameService.idFindGameData(payload._id);
        res.send({
            code: 1,
            userData: result,
            gameData: result2
        })
    },
    notice: async (req, res) => {
        const result = await GameService.notice();
        res.send({
            code: 1,
            data: result
        })
    },
    gameLog: async (req, res) => {
        let payload = JWT.verify(req.headers["authorization"].split(" ")[1])//解析token 获取id
        const { e, w } = req.body;
        if (w === 1) {
            await GameService.winTimeUp(payload._id);
        }
        await GameService.gameLog(payload._id, e, w);
        res.send({
            code: 1
        })
    },
    getGameLog: async (req, res) => {
        let payload = JWT.verify(req.headers["authorization"].split(" ")[1])//解析token 获取id
        const result = await GameService.idFindGamelog(payload._id);

        const res4 = '[' + result[0].enemyId.slice(3) + ']';
        const jsonArray = JSON.parse(res4)
        
        //console.log(jsonArray)
        // jsonArray.forEach(async (item) => {
        //     const res3 = await UserService.idGetUsername(item.e);
        //     item.e = res3[0].username;
        // })

        for (const item of jsonArray) {
            const res3 = await UserService.idGetUsername(item.e);
            item.e = res3[0].username;
        }
        res.send({
            code: 1,
            data: jsonArray
        })
    }
}


module.exports = UserContoller